import React from "react";
import { Upload, Button, Icon, message /** , Typography */, Modal } from "antd";
// import Zmage from "react-zmage";
import { openNotificationWithIcon } from 'utils/comm';
import { getFileUrl } from "services/public.js";
import VideoPlayerModal from 'components/VideoPlayerModal';
import Image from '@ali-whale/image'

// import 'react-zmage/lib/zmage.css';

// const { Paragraph } = Typography;

const buttonStyle = {
  color: "#bfbfbf",
  // maxWidth: '198px',
  overflow: "hidden",
  textOverflow: "ellipsis",
  whiteSpace: "nowrap",
};

const templateStyle = {
  marginTop: "16px",
  display: "flex",
  lineHeight: "24px",
};

const imageExtensions = [
  'jpeg', 'gif', 'png', 'jpg', 'svg', 'bmp',
];
const videoExtensions = [
  'webm', 'mp4',
];

const isImage = (name) => {
  try {
    const ext = name.split('.').pop().toLowerCase()
    return imageExtensions.indexOf(ext) > -1;
  } catch(e) {
    return false;
  }
}
const isVideo = (name) => {
  try {
    const ext = name.split('.').pop().toLowerCase()
    return videoExtensions.indexOf(ext) > -1;
  } catch(e) {
    return false;
  }
}

function toFormValue(value) {
  function formatFileList(arr) {
    return arr
      .map((item) => {
        const { name, datas } = item;
        if (datas) {
          return { name, datas }; // 只提交成功的数据
        } else {
          return null;
        }
      })
      .filter(Boolean);
  }
  if (Array.isArray(value)) {
    return formatFileList(value);
  }
  const result = JSON.parse(value);
  if (Array.isArray(result)) {
    return formatFileList(result);
  }
  return [];
}
function toUploadValue(value) {
  function formatFileList(arr) {
    return arr
      .map((item, idx) => {
        const { name: fileName, response, uid } = item;
        let { datas, status } = item;
        if (datas) { // 服务端格式 { datas, name }
          status = 'done';
        } else if (status === 'done') {
          ({ datas } = response);
        }
        if (datas) {
          return {
            name: fileName,
            status: "done",
            uid: uid || -idx,
            url: getFileUrl(datas),
            datas,
          };
        } else {
          return item; // 上传中/出错的文件不做处理
        }
      })
      .filter(Boolean);
  }
  if (Array.isArray(value)) {
    return formatFileList(value);
  }
  const result = JSON.parse(value);
  if (Array.isArray(result)) {
    return formatFileList(result);
  }
  return [];
}
class CustomUploadField extends React.Component {
  static getDerivedStateFromProps(nextProps, prevState) {
    // Should be a controlled component.
    const { fileList } = prevState;
    if (Array.isArray(nextProps.value) && nextProps.value && nextProps.value.length > 0) {
      const datasMap = fileList.reduce((m, { datas, response }) => {
        if (datas) {
          m[datas] = true;
        } else if (response && response.datas) {
          m[response.datas] = true;
        }
        return m;
      }, {});
      const newValue = nextProps.value.filter(({ datas }) => !datasMap[datas]);
      if (newValue.length > 0) {
        return {
          fileList: [...fileList, ...toUploadValue(newValue)],
        };
      }
    }
    return null;
  }

  constructor(props) {
    super(props);
    const { params: data = {}, itemProps = {} } = this.props;
    let vals = [];
    // const { value: vals = [] } = data;
    const { params = {} } = data;
    const { template } = params;

    if (data.value instanceof Array) {
      vals = data.value;
    }

    /*
    const newValue = vals.map((item, index) => {
      // console.log("key:", key);
      const keys = Object.keys(item)[0];
      return {
        uid: index,
        name: keys,
        url: getFileUrl(item[keys]),
        status: "done",
      };
    });
    */

    const newValue = toUploadValue(vals);
    this.state = {
      fileList: newValue,
      annex: template || itemProps.template || [],
      videoPreviewUrl: null,
      imageVisibile: false,
      imageUrl: null,
    };
    this.uploadProps = {
      action: "/flow-platform/file/add",
      onChange: this.onFileChange,
      beforeUpload: this.beforeUpload,
      defaultFileList: [],
    };
  }

  componentDidMount() {}

  componentWillUnmount() {}

  onFileChange = ({ /* file, */ fileList }) => {
    const { params: data = {} } = this.props;
    const { params = {} } = data;
    // if (file.status !== "uploading") {
      // this.triggerChange(fileList);
    // }
    const setNewFileList = (originFileList) => {
      const newFileList = toUploadValue(originFileList);
      this.triggerChange(newFileList);
      this.setState({ fileList: newFileList });
    }
    if (params.multiple === false) {
      /*
      const isHas = fileList.some((ele) => ele.status === "done");
      if (!isHas) {
        */
      const validFiles = fileList.filter((ele) => ele.status === "done" || ele.status === 'uploading' || !ele.status);
      if (validFiles.length < 2) {
        setNewFileList(fileList);
      }
    } else {
      setNewFileList(fileList);;
    }
  };

  beforeUpload = () => {
    const { fileList } = this.state;
    const { params: data = {} } = this.props;
    const { params = {} } = data;
    if (params.multiple === false) {
      const isHas = fileList.some((ele) => ele.status === "done");
      if (isHas) {
        message.warn("不允许上传多个附件");
        return Promise.reject();
      }
    }
    return Promise.resolve();
  };

  triggerChange = (changedValue) => {
    // Should provide an event to pass value to Form.
    const { onChange } = this.props;
    if (onChange) {
      onChange(toFormValue(changedValue));
    }
  };

  hideVideoPreview = () => {
    this.setState({ videoPreviewUrl: null });
  }

  handleCancel = () => {
    this.setState({
      imageVisibile: false,
    });
  };

  render() {
    const { uploadProps = {}, itemProps = {} } = this.props;
    const newProps = { ...this.uploadProps, ...uploadProps, ...itemProps };
    if (newProps.disabled) {
      newProps.showUploadList = {
        showRemoveIcon: false,
      };
    }
    const { showPreview = false, placeholder, contentpart = false, ...restProps } = itemProps;
    const { videoPreviewUrl, fileList, annex, imageVisibile, imageUrl } = this.state;
    const hint = placeholder || "上传文件";
    return (
      <div>
        <Upload
          {...newProps}
          fileList={fileList}
          {...(showPreview ? 
            ({
              showUploadList: {
                showPreviewIcon: true,
                showRemoveIcon: true,
                showDownloadIcon: true,
              },
              onPreview: (file) => {
                if (isImage(file.name)) {
                  this.setState({imageVisibile: true, imageUrl: file.url })
                  //  Zmage.browsing({ src: file.url, zIndex: 10001 });
                } else if (isVideo(file.name)) {
                  this.setState({ videoPreviewUrl: file.url });
                  // openNotificationWithIcon('info', '提示', '暂不支持该类型文件预览，请下载后查看');
                } else {
                  openNotificationWithIcon('info', '提示', '暂不支持该类型文件预览，请下载后查看');
                  // window.open(file.url);
                }
                /*
                if (newProps.onDownload) {
                  newProps.onDownload(file);
                }
                */
              },
            }): null)
          }
        >
          <Button
            {...restProps}
            style={buttonStyle}
            // title={hint}
          >
            <Icon type="upload" />
            {hint}
          </Button>
        </Upload>
        {!contentpart && annex.length > 0 && (
          <div style={templateStyle}>
            附件模板：
            <div style={{ flex: 1 }}>
              {annex.map((item, index) => {
                return (
                  <>
                    <a
                      key={index}
                      style={{ textDecoration: "underline" }}
                      href={item.url}
                      title={item.fileName}
                    >
                      {item.fileName}
                    </a>
                    &nbsp; &nbsp;
                  </>
                );
              })}
            </div>
          </div>
        )}
        <VideoPlayerModal
          url={videoPreviewUrl}
          visible={!!videoPreviewUrl}
          footer={(
            <Button onClick={this.hideVideoPreview}>关闭</Button>
          )}
          onCancel={this.hideVideoPreview}
        />
        <Modal
          width="800px"
          visible={imageVisibile}
          onCancel={this.handleCancel}
          footer={null}
          bodyStyle={{ height: 400, display: 'flex', justifyContent: 'space-around' }}
        >
          <Image 
            src={[{url: imageUrl}]}
            width="600"
            height="350"
          />
        </Modal>
      </div>
    );
  }
}
export default CustomUploadField;
